<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Message;
use yii\data\Sort;
/**
 * MessageSearch represents the model behind the search form about `app\models\Message`.
 */
class MessageSearch extends Message
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['message_id', 'sender_id', 'receiver_id', 'messageText_id', 'isRead', 'status'], 'integer'],
            [['title', 'create_date'], 'safe'],
        ];
    }

    /**
     * return the read Options 
     * @author : nonglei 
     * @date   : 22/04/2014
     */
    public function getIsReadOptions()
    {
        return array(
            Message::FLAG_READ=>'Read',
            Message::FLAG_UNREAD=>'Unread',
        );
    }


    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params,$type)
    {
        if($type == "inbox")
        {
            $query = Message::find()->where('status != :status and receiver_id = :receiver_id order by message_id DESC',[':status'=>1, ':receiver_id'=>yii::$app->user->identity->user_id]);
        }
        else
        {
            $query = Message::find()->where('status != :status and sender_id = :sender_id order by message_id DESC',[':status'=>0, ':sender_id'=>yii::$app->user->identity->user_id]);
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'message_id' => $this->message_id,
            'sender_id' => $this->sender_id,
            'receiver_id' => $this->receiver_id,
            'messageText_id' => $this->messageText_id,
            'create_date' => $this->create_date,
            'isRead' => $this->isRead,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title]);

        return $dataProvider;
    }
}
